# 用于直观地显示HSV范围包含的颜色

import cv2
import matplotlib.pyplot as plt
import numpy


def display_multiple_hsv_ranges(hsv_ranges, titles=None, width=255, height=255):
    num_ranges = len(hsv_ranges)
    fig, axes = plt.subplots(1, num_ranges, figsize=(num_ranges * 4, 4))

    for i, (hsv_min, hsv_max) in enumerate(hsv_ranges):
        # 创建一个空白的HSV图像
        hsv_img = numpy.zeros((height, width, 3), dtype=numpy.uint8)

        # 计算每列和每行的HSV值
        for y in range(height):
            for x in range(width):
                h = int(hsv_min[0] + (hsv_max[0] - hsv_min[0]) * y / (height - 1))
                s = int(hsv_min[1] + (hsv_max[1] - hsv_min[1]) * x / (width - 1))
                v = int(hsv_min[2] + (hsv_max[2] - hsv_min[2]) * (height - y) / height)
                hsv_img[y, x] = [h, s, v]

        # 将HSV图像转换为BGR（因为OpenCV默认使用BGR）
        bgr_img = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2BGR)

        # 使用Matplotlib显示图像
        if num_ranges > 1:
            ax = axes[i]
        else:
            ax = axes
        ax.imshow(cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB))
        ax.set_title(titles[i] if titles and i < len(titles) else 'HSV Color Range')
        ax.axis('off')  # 关闭坐标轴

    plt.tight_layout()
    plt.show()


# 示例用法：
color_to_hsv = {"yellow": (numpy.array([20, 80, 236]), numpy.array([30, 255, 255])),
                "red": (numpy.array([150, 80, 236]), numpy.array([190, 255, 255]))}

display_multiple_hsv_ranges(list(color_to_hsv.values()), titles=list(color_to_hsv.keys()))
